package com.sdtv.basemodule.utils;

import java.nio.charset.Charset;
import java.util.Map;

import okhttp3.MediaType;

/**
 * @ProjectName: MediunFusion
 * @Package: com.sdtv.basemodule.utils
 * @ClassName: HttpUtil
 * @Description: HTTP相关校验
 * @Author: 小郭同学
 * @CreateDate: 2019-06-20 15:44
 * @UpdateRemark: 更新说明
 * @Version: 1.0
 */
public class HttpUtil {

    public static final Charset UTF8 = Charset.forName("UTF-8");

    /**
     * 检查是否为空
     *
     * @param t
     * @param message
     * @param <T>
     * @return
     */
    public static <T> T checkNotNull(T t, String message) {
        if (t == null) {
            throw new NullPointerException(message);
        }
        return t;
    }


    /**
     * 参数拼接url
     */
    public static String createUrlFromParams(String url, Map<String, String> params) {
        try {
            StringBuilder sb = new StringBuilder();
            sb.append(url);
            if (url.indexOf('&') > 0 || url.indexOf('?') > 0) {
                sb.append("&");
            } else {
                sb.append("?");
            }
            for (Map.Entry<String, String> urlParams : params.entrySet()) {
                String urlValues = urlParams.getValue();
                //对参数进行 utf-8 编码,防止头信息传中文
                sb.append(urlParams.getKey()).append("=").append(urlValues).append("&");
            }
            sb.deleteCharAt(sb.length() - 1);
            return sb.toString();
        } catch (Exception e) {

        }
        return url;
    }


    /**
     * 返回类型判断
     *
     * @param mediaType
     * @return
     */
    public static boolean isText(MediaType mediaType) {
        if (mediaType == null) {
            return false;
        }
        if (mediaType.type() != null && mediaType.type().equals("text")) {
            return true;
        }
        if (mediaType.subtype() != null) {
            if (mediaType.subtype().equals("json")) {
                return true;
            }
        }
        return false;
    }


}
